"""
@Author: li
@Email: lijianqiao2906@live.com
@FileName: user.py
@DateTime: 2025/07/07
@Docs: 用户管理及用户设置API
"""

from typing import cast

from fastapi import APIRouter, Depends, HTTPException, status

from app.models import User
from app.models.system import UserSettings
from app.schemas.base import PaginatedResponse
from app.schemas.system import UserSettingsRead, UserSettingsUpdate
from app.schemas.user import AssignRolesRequest, UserCreate, UserRead, UserUpdate
from app.services.system import user_settings_service
from app.services.user import user_service
from app.utils.deps import CurrentUserDep, PaginationDep, PermissionChecker

router = APIRouter()


@router.get(
    "/",
    response_model=PaginatedResponse[UserRead],
    summary="获取用户分页列表",
    dependencies=[Depends(PermissionChecker("user:read"))],
)
async def get_users_list(
    pagination: PaginationDep,
) -> PaginatedResponse[UserRead]:
    """
    获取带有分页信息的用户列表。
    需要 `user:read` 权限。
    """
    users_models, total = await user_service.get_active_paginated(order_by=["-created_at"], **pagination)
    return PaginatedResponse(
        total=total,
        page=pagination["page"],
        page_size=pagination["page_size"],
        data=[UserRead.model_validate(user) for user in users_models],
    )


@router.post(
    "/",
    response_model=UserRead,
    summary="创建新用户",
    dependencies=[Depends(PermissionChecker("user:create"))],
    status_code=status.HTTP_201_CREATED,
)
async def create_user(user_in: UserCreate) -> User:
    """
    创建一个新用户。
    需要 `user:create` 权限。
    """
    return await user_service.create_user(user_in)


@router.get(
    "/{user_id}",
    response_model=UserRead,
    summary="获取指定用户信息",
    dependencies=[Depends(PermissionChecker("user:read"))],
)
async def get_user_by_id(user_id: int) -> User:
    """
    获取指定ID的用户详细信息。
    需要 `user:read` 权限。
    """
    user = await user_service.get_active_by_id(user_id)
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
    return cast(User, user)


@router.put(
    "/{user_id}",
    response_model=UserRead,
    summary="更新用户信息",
    dependencies=[Depends(PermissionChecker("user:update"))],
)
async def update_user(user_id: int, user_in: UserUpdate) -> User:
    """
    更新指定ID的用户信息。
    需要 `user:update` 权限。
    """
    return await user_service.update_user(user_id, user_in)


@router.delete(
    "/{user_id}",
    status_code=status.HTTP_204_NO_CONTENT,
    summary="删除用户",
    dependencies=[Depends(PermissionChecker("user:delete"))],
)
async def delete_user(user_id: int) -> None:
    """
    软删除指定ID的用户。
    需要 `user:delete` 权限。
    """
    await user_service.soft_delete(user_id)
    return None


@router.post(
    "/{user_id}/roles",
    response_model=UserRead,
    summary="为用户分配角色",
    dependencies=[Depends(PermissionChecker("user:assign_roles"))],
)
async def assign_roles_to_user(user_id: int, roles_in: AssignRolesRequest) -> User:
    """
    为指定用户分配角色。
    需要 `user:assign_roles` 权限。
    """
    user_model = await user_service.assign_roles(user_id, roles_in.role_ids)
    return cast(User, user_model)


# --- 当前用户设置 ---


@router.get(
    "/me/settings",
    response_model=UserSettingsRead,
    summary="获取当前用户的个人设置",
)
async def get_my_settings(current_user: CurrentUserDep) -> UserSettings:
    """
    获取当前登录用户的个人化配置。
    如果不存在，会返回默认值。
    """
    settings = await user_settings_service.get_by_user_id(current_user.id)
    if not settings:
        # 如果用户没有设置，可以返回一个默认的或者创建一个
        # 这里我们选择创建一个默认设置并返回
        default_settings_in = UserSettingsUpdate()
        settings = await user_settings_service.create_or_update_by_user_id(current_user.id, default_settings_in)
    return settings


@router.put(
    "/me/settings",
    response_model=UserSettingsRead,
    summary="更新当前用户的个人设置",
)
async def update_my_settings(
    settings_in: UserSettingsUpdate,
    current_user: CurrentUserDep,
) -> UserSettings:
    """
    更新当前登录用户的个人化配置。
    """
    return await user_settings_service.create_or_update_by_user_id(current_user.id, settings_in)
